package com.zhuifeng.product.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.zhuifeng.product.domain.ProductRequest;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.zhuifeng.common.core.domain.R;
import com.zhuifeng.orders.domain.OrdersDetails;
import com.zhuifeng.product.domain.ProductSku;
import com.zhuifeng.utils.OssUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import com.zhuifeng.common.log.annotation.Log;
import com.zhuifeng.common.log.enums.BusinessType;
import com.zhuifeng.common.security.annotation.RequiresPermissions;
import com.zhuifeng.product.domain.Product;
import com.zhuifeng.product.service.IProductService;
import com.zhuifeng.common.core.web.controller.BaseController;
import com.zhuifeng.common.core.web.domain.AjaxResult;
import com.zhuifeng.common.core.utils.poi.ExcelUtil;
import com.zhuifeng.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商品Controller
 *
 * @author zhuifeng
 * @date 2022-08-18
 */
@RestController
@RequestMapping("/product")
public class ProductController extends BaseController
{
    @Autowired
    private IProductService productService;

    /**
     * 查询个人中心表列表
     */
    @RequiresPermissions("product:product:getProductDetails")
    @PostMapping("/getProductDetails/{productId}")
    public R getProductDetails(@PathVariable("productId") String productId)
    {
        Map<String , Object> map = productService.getProductDetails(productId);
        return R.ok(map);
    }

    /**
     * 查询个人中心表列表
     */
    @RequiresPermissions("product:product:productSold")
    @PostMapping("/productSold/{productId}")
    public R productSold(@PathVariable("productId")String productId)
    {
        productService.productSold(productId);
        return R.ok();
    }

    /**
     * 商品上架接口
     */
    @RequiresPermissions("product:product:productPutaway")
    @PostMapping("/productPutaway/{productId}")
    public R productPutaway(@PathVariable("productId")String productId)
    {
        productService.productPutaway(productId);
        return R.ok();
    }

    /**
     * 查询商品列表
     */
    @RequiresPermissions("product:product:list")
    @GetMapping("/list")
    public TableDataInfo list(Product product)
    {
        startPage();
        List<Product> list = productService.selectProductList(product);
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @RequiresPermissions("product:product:export")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Product product)
    {
        List<Product> list = productService.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 获取商品详细信息
     */
    @RequiresPermissions("product:product:query")
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable("productId") String productId)
    {
        return AjaxResult.success(productService.selectProductByProductId(productId));
    }



    /**
     * 新增商品
     */
    @RequiresPermissions("product:product:add")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProductRequest productRequest)
    {
        return toAjax(productService.insertProduct(productRequest));
    }

    /**
     * 修改商品
     */
    @RequiresPermissions("product:product:edit")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProductRequest productRequest)
    {
        return toAjax(productService.updateProduct(productRequest));
    }

    /**
     * 删除商品
     */
    @RequiresPermissions("product:product:remove")
    @Log(title = "商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{productIds}")
    public AjaxResult remove(@PathVariable String[] productIds)
    {
        return toAjax(productService.deleteProductByProductIds(productIds));
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile multipartFile){

        String s = OssUtil.uploadMultipartFile(multipartFile);

        return s;
    }

//    @ApiOperation("图片上传")
//    @RequestMapping(value="/saveFile",produces="application/json;charset=UTF-8")
//    @ResponseBody
//    public R filesUpload(@RequestParam(value = "myfiles" ) MultipartFile[] files,
//                                    HttpServletRequest request) {
//        List<String> list = new ArrayList<>();
//        if (files != null && files.length > 0) {
//            for (int i = 0; i < files.length; i++) {
//                MultipartFile file = files[i];
//                // 保存文件
//                list = saveFile(request, file, list);
//            }
//        }
//        //测试
//        for (int i = 0; i < list.size(); i++) {
//            System.out.println("集合里面的数据" + list.get(i));
//        }
//        // 数组转String字符串
//        String newStr = StringUtils.join(list, ",");
//        System.out.println(newStr);
//        return R.ok(newStr);
//    }
//
//    private List<String> saveFile(HttpServletRequest request,
//                                  MultipartFile file, List<String> list) {
//        // 判断文件是否为空
//        if (!file.isEmpty()) {
//            try {
//                // 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
//                // )
//                String filePath = "/project/tomcat/webapps/fileUpload/picture" + (new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + file.getOriginalFilename());
//
//                list.add(filePath);
//                File saveDir = new File(filePath);
//                if (!saveDir.getParentFile().exists()) {
//                    saveDir.getParentFile().mkdirs();
//                }
//
//                // 转存文件
//                file.transferTo(saveDir);
//                return list;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return list;
//    }

    /**
     * 修改商品Sku库存数据
     */
    @PostMapping("/updateProductSkuStock")
    public R updateProductSkuStock(@RequestBody ProductSku productSku){
        this.productService.updateProductSkuStock(productSku);
        return R.ok();
    }

    /**
     * 删除订单加库存
     * @return
     */
    @Bean
    public Queue initQueue(){
        return new Queue("zhuifeng_deduction_inventory");
    }

    @RabbitListener(queues = {"zhuifeng_deduction_inventory"})
    public void deductionInventory(String inventoryJson, Message message, Channel channel){
        try {
            OrdersDetails ordersDetails = JSONObject.parseObject(inventoryJson, OrdersDetails.class);
            //修改库存
            this.productService.updateProductSkuInventory(ordersDetails);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成订单减库存
     */
    @Bean
    public Queue subtractInventory(){
        return new Queue("zhuifeng_subtract_inventory");
    }

    @RabbitListener(queues = {"zhuifeng_subtract_inventory"})
    public void deductionSubtractInventory(String inventoryJson, Message message, Channel channel){
        try {
            OrdersDetails ordersDetails = JSONObject.parseObject(inventoryJson, OrdersDetails.class);
            //修改库存
            this.productService.updateProductSkuSubtractInventory(ordersDetails);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 确认收货
     */
    @Bean
    public Queue initAffirmReceiving(){
        return new Queue("affirm_receiving");
    }

    @RabbitListener(queues = {"affirm_receiving"})
    public void affirmReceivingInventory(String inventoryJson, Message message, Channel channel){
        try {
            OrdersDetails ordersDetails = JSONObject.parseObject(inventoryJson, OrdersDetails.class);
            //修改库存
            this.productService.updateProductSkuAffirmReceivingInventory(ordersDetails);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
